// 关于滚动到底部的代码逻辑
import { onMounted, onUnmounted } from "@vue/runtime-core";
import { ref } from 'vue'
import { throttle } from "underscore";

export default function useScroll() {
    // 初始默认为没有到底
    const isReachBottom = ref(false)
    const scrollTop = ref(0)
    const clientHeight = ref(0)
    const scrollHeight = ref(0)

    const scrollBottomListener = throttle(() => {
        // 当前位置到顶部的距离
        scrollTop.value = document.documentElement.scrollTop
        // 屏幕的长度
        clientHeight.value = document.documentElement.clientHeight
        // 页面总体长度
        scrollHeight.value = document.documentElement.scrollHeight

        // 滚动到底部:提前一点刷新
        if (scrollHeight.value <= scrollTop.value + clientHeight.value + 1) {
            console.log('滚动到底部')
            isReachBottom.value = true
        }

        // console.log(scrollTop.value)
    }, 100)

    onMounted(() => {
        window.addEventListener('scroll', scrollBottomListener)
    })

    onUnmounted(() => {
        window.removeEventListener('scroll', scrollBottomListener)
    })

    return { isReachBottom, scrollHeight, clientHeight, scrollTop }
}